﻿#include <iostream>
#include <unordered_set>
#include <queue>
#include <vector>
using namespace std;

class Solution
{
public:
    // 127. 单词接龙
    int ladderLength(string beginWord, string endWord, vector<string>& wordList)
    {
        unordered_set<string> hash(wordList.begin(), wordList.end());
        unordered_set<string> vis;

        if (!hash.count(endWord))
            return 0;

        queue<string> q;
        q.push(beginWord);
        vis.insert(beginWord);

        int ret = 1;
        while (q.size())
        {
            ret++;
            int sz = q.size();

            while (sz--)
            {
                string t = q.front();
                q.pop();

                for (int i = 0; i < t.size(); i++)
                {
                    string tmp = t;
                    for (char ch = 'a'; ch <= 'z'; ch++)
                    {
                        tmp[i] = ch;
                        if (!vis.count(tmp) && hash.count(tmp))
                        {
                            if (tmp == endWord)
                                return ret;
                            q.push(tmp);
                            vis.insert(tmp);
                        }
                    }
                }
            }
        }
        return 0;
    }
};

int main()
{
    vector<string> v{ "hot","dot","dog","lot","log","cog" };
    cout << Solution().ladderLength("hit", "cog", v) << endl;

    return 0;
}